<script setup>
import topNav from "../../components/topNav.vue";
import {
  onMounted,
  reactive,
  ref,
  getCurrentInstance,
  computed,
  nextTick,
} from "vue";
import { onLoad, onReachBottom } from "@dcloudio/uni-app";
import { salePriceCreate } from "@/services/goods";
import {
  appStockListQuery,
  getDamageReason,
  getDamageCreate,
} from "@/services/cashier";
import { base_URL } from "@/utils/http";

import { operation } from "@/utils/num.js";

// @param op { string } 运算类型，有加减乘除（add / subtract / multiply / divide）

// import tabbarView from "../components/tabbar.vue";
const scrollTop = ref(0);
const code = ref("");

onLoad((option) => {
  code.value = option.code ? option.code : "";
  form.value.keyword = option.code ? option.code : "";
  getDamageReasonFun();
});
const saveFun = () => {
  // console.log("取消");
  // form.value.name = "";
  // loading.value = "";
  // getappStockListQuery(1);
};

const searchFun = (val) => {
  console.log("取2消");
  form.value.keyword = val;
  loading.value = "";
  console.log(form.value.name);
  getappStockListQuery(1);
};

onReachBottom(() => {
  console.log("触底了");
  getappStockListQuery();
});
onMounted(() => {
  getappStockListQuery();
});

//获取商品
const form = ref({
  categoryId: "",
  pageIndex: 1,
  pageSize: 20,
  barCode: "",
  code: "",
  name: "",
  skuCode: "",
  categoryId: "",
  available: "",
  keyword: "",
});

const productData = ref([]);

const loading = ref("");
const getappStockListQuery = async (index) => {
  if (index == 1) {
    productData.value = [];
  }
  if (index) {
    form.value.pageIndex = index;
  }
  if (loading.value == "noMore") {
    return;
  }
  loading.value = "Loading";
  try {
    let res = await appStockListQuery(form.value);
    if (res.code == 200) {
      productData.value = productData.value.concat(res.data.datas);
      console.log(productData.value);
      form.value.pageIndex = form.value.pageIndex + 1;

      if (res.data.datas.length < form.value.pageSize) {
        loading.value = "noMore";
      } else {
        loading.value = "More";
      }
    } else {
    }

    console.log(res);
  } catch (e) {}
};

//改价模块
const itemObj = ref({});
const selectitem = ref(0);
const num = ref(0);
const show = ref(false);
const showKeyboard = ref(true);
const priceValue = ref("30.10");
const keyboard = ref(null);
const keyboardHeight = ref(0);
const isSr = ref(false);
const themeVars = ref({
  numberKeyboardBackground: "#F7F8FA ",
  numberKeyboardKeyBackground: "#FFFFFF",
  numberKeyboardButtonBackground: "#FF5722",
});

const onClickItem = (item, index) => {
  if (item.bcStockNum) {
    priceValue.value = item.bcStockNum;
  } else {
    priceValue.value = "0";
  }
  if (item.damageCertificate) {
  } else {
    item.damageCertificate = [];
  }
  itemObj.value = item;
  selectitem.value = index;

  selectNumIndex.value = -1;
  nextTick(() => {
    keyWord.value.open();
  });
  // show.value = true;
  // showKeyboard.value = true;
  // nextTick(() => {
  //   setTimeout(() => {
  //     keyboardHeight.value = keyboard.value.$el.offsetHeight;
  //     console.log(keyboard.value.$el.offsetHeight, keyboard.value);
  //   }, 100);
  // });
};
const onInput = (item) => {
  setTimeout(() => {
    priceValue.value = handlePriceInput(priceValue.value);
  }, 100);

  console.log(item);
};
const handlePriceInput = (event) => {
  let value = event;

  // 过滤掉非数字和小数点的字符
  value = value.replace(/[^0-9.]/g, "");

  // 确保只有一个小数点
  const parts = value.split(".");
  if (parts.length > 2) {
    value = parts[0] + "." + parts.slice(1).join("");
  }

  // 如果以小数点开头，添加 '0'
  if (value.startsWith(".")) {
    value = "0" + value;
  }

  // 如果小数点后超过两位，截断
  const decimalParts = value.split(".");
  if (decimalParts.length === 2 && decimalParts[1].length > 2) {
    value = decimalParts[0] + "." + decimalParts[1].slice(0, 2);
  }
  console.log("value", value);
  // form.value.price = value;
  return value;
};
//提交改价

const onBlue = async () => {
  try {
    let res = await salePriceCreate({
      productId: itemObj.value.id,
      revisePrice: priceValue.value,
      description: "手机端操作",
    });
    if (res.code == 200) {
      showToast("修改成功");
      num.value = num.value + 1;
      productData.value[selectitem.value].newsalePrice = priceValue.value;
      // productData.value[selectitem.value].salePrice=priceValue.value

      // getappStockListQuery(1);
      show.value = false;
    } else {
      showToast(res.msg);
    }
  } catch (e) {
    showToast(e.msg);
  }
};
const goRecordone = () => {
  if (products.value.length <= 0) {
    uni.showToast({
      title: "请先选择商品",
      icon: "none",
    });
    return;
  }

  shoRow.value = true;
};
const goRecord = () => {
  let data = [];

  products.value.forEach((item) => {
    console.log(item.damageCertificate, item);
    data.push({
      productId: item.id,
      stockNum: item.bcStockNum,
      damageReasonId: item.damageReasonId,
      damageCertificate: item.damageCertificate.map((res) => res.url),
    });
  });
  console.log(data);
  try {
    getDamageCreate({ description: "", products: data }).then((res) => {
      if (res.code == 200) {
        uni.showToast({
          title: "提交成功",
          icon: "none",
        });
        setTimeout(() => {
          uni.reLaunch({
            url: "/pages/loss/home/index",
          });
        }, 1000);
      }
    });
  } catch (e) {}
};

const keyWord = ref(null);
const selectNumIndex = ref(-1);
const showInputSelect = ref(false);
const del = (e) => {
  showInputSelect.value = true;
  if (e == 0) {
    selectNumIndex.value = selectNumIndex.value - 1;
  } else if (e == 1) {
    selectNumIndex.value = selectNumIndex.value + 1;
  }
};
const keyWordItem = (index) => {
  showInputSelect.value = true;
  selectNumIndex.value = index;
};
//金额键盘
const inp = (e) => {
  showInputSelect.value = true;
};

const hide = () => {
  showInputSelect.value = false;
  if (num.value > 0) {
    // numblur();
  } else {
    jsnum.value = 0;
  }
  isinputto.value = false;
  isshowput.value = true;
};
const confirm = async () => {
  // getcomputeBrokerage(Number(num.value));
  if (itemObj.value.damageCertificate.length <= 0) {
    uni.showToast({
      title: "请上传凭证",
      icon: "none",
    });

    return;
  }
  if (priceValue.value <= 0) {
    uni.showToast({
      title: "请输入报损数量",
      icon: "none",
    });

    return;
  }
  if (!itemObj.value.damageReasonId) {
    uni.showToast({
      title: "请选择报损原因",
      icon: "none",
    });
    return;
  }
  if (isUpload.value) {
    uni.showToast({
      title: "图片上传中",
      icon: "none",
    });
    return;
  }

  itemObj.value.bcStockNum = priceValue.value;
  if (products.value.length > 0) {
    products.value.forEach((item, index) => {
      if (item.id == itemObj.value.id) {
        products.value[index] = itemObj.value;
      } else {
        products.value.push(itemObj.value);
      }
    });
  } else {
    products.value.push(itemObj.value);
  }

  numValue.value = 0;
  priceValueToa.value = 0;
  products.value.forEach((item) => {
    numValue.value = operation(
      numValue.value,
      Number(item.bcStockNum),
      2,
      "add"
    );
    priceValueToa.value = operation(
      priceValueToa.value,
      operation(Number(item.bcStockNum), item.taxPrice, 2, "multiply"),
      2,
      "add"
    );
  });

  keyWord.value.close();
};
const numblur = () => {
  // getcomputeBrokerage(Number(num.value));
};
const closePay = () => {
  keyWord.value.close();
};
const isUpload = ref(false);
// 删除图片
const deletePic = (event) => {
  itemObj.value.damageCertificate.splice(event.index, 1);
};
// 新增图片
const afterRead = async (event) => {
  isUpload.value = true;
  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  let lists = [].concat(event.file);
  let fileListLen = itemObj.value.damageCertificate.length;
  lists.map((item) => {
    itemObj.value.damageCertificate.push({
      ...item,
      status: "uploading",
      message: "上传中",
    });
  });
  for (let i = 0; i < lists.length; i++) {
    try {
      const result = await uploadFilePromise(lists[i].url);

      let item = itemObj.value.damageCertificate[fileListLen];
      itemObj.value.damageCertificate.splice(fileListLen, 1, {
        ...item,
        status: "success",
        message: "",
        url: result.data.url,
      });

      fileListLen++;
      console.log(fileListLen, lists.length);
      if (fileListLen == lists.length) {
        isUpload.value = false;
      }
    } catch (e) {
      console.log(e);
      isUpload.value = false;

      itemObj.value.damageCertificate.splice(i, 1);
      uni.showToast({
        title: e.message,
        icon: "none",
      });
    }
  }
};

const uploadFilePromise = (url) => {
  return new Promise((resolve, reject) => {
    let a = uni.uploadFile({
      url: base_URL + "/app/product/image", // 仅为示例，非真实的接口地址
      filePath: url,
      header: {
        "X-Auth-Token": uni.getStorageSync("X-Auth-Token"),
      },
      name: "file",
      formData: {
        user: "test",
      },
      success: (res) => {
        let data = JSON.parse(res.data);
        if (data.code == 200) {
          setTimeout(() => {
            resolve(data);
          }, 1000);
        } else {
          reject(data);
        }
      },
    });
  });
};
const ishowcamera = ref(false);
const scanFun = () => {
  console.log("扫码");
  // #ifdef H5
  uni.navigateTo({ url: "/pages/code_sand/index?type=price" });
  // #endif
  // 允许从相机和相册扫码
  // #ifdef APP-PLUS
  const systemInfo = uni.getSystemInfoSync();
  if (systemInfo.osName === "android") {
    if (uni.getStorageSync("isspermission")) {
    } else {
      ishowcamera.value = true;
    }

    plus.android.requestPermissions(["android.permission.CAMERA"], (e) => {
      if (e.deniedAlways.length > 0) {
        // 弹出提示框解释为何需要权限，引导用户打开设置页面开启

        ishowcamera.value = false;
      } else if (e.deniedPresent.length > 0) {
        //权限被临时拒绝
        // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限
        ishowcamera.value = false;
      } else if (e.deniedAlways.length > 0) {
        //权限被永久拒绝
        // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限
        ishowcamera.value = false;
      } else {
        plus.android.requestPermissions(
          ["android.permission.READ_EXTERNAL_STORAGE"],
          (e) => {
            if (e.deniedAlways.length > 0) {
              // 弹出提示框解释为何需要权限，引导用户打开设置页面开启

              ishowcamera.value = false;
            } else if (e.deniedPresent.length > 0) {
              //权限被临时拒绝
              // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限

              ishowcamera.value = false;
            } else if (e.deniedAlways.length > 0) {
              //权限被永久拒绝
              // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限

              ishowcamera.value = false;
            } else {
              ishowcamera.value = false;
              uni.setStorageSync("isspermission", true);

              uni.scanCode({
                scanType: ["barCode", "qrCode"],
                autoDecodeCharset: true,
                autoZoom: true,
                success: function (res) {
                  console.log("条码类型：" + res.scanType);
                  console.log("条码内容：" + res.result);
                  form.value.keyword = res.result;
                  code.value = res.result;
                  getappStockListQuery(1);

                  // uni.navigateTo({
                  //   url: "/pages/goods/goods_price_search/index?code=" + res.result,
                  // });
                },
              });
            }
          }
        );
      }
    });
    return;
  }
  uni.scanCode({
    scanType: ["barCode", "qrCode"],
    autoDecodeCharset: true,
    autoZoom: true,
    success: function (res) {
      console.log("条码类型：" + res.scanType);
      console.log("条码内容：" + res.result);
      form.value.keyword = res.result;
      code.value = res.result;
      getappStockListQuery(1);

      // uni.navigateTo({
      //   url: "/pages/goods/goods_price_search/index?code=" + res.result,
      // });
    },
  });
  // #endif
};

//库存报损原因
const damageReason = ref([]);
const damageReasonShow = ref(false);
const products = ref([]);

const getDamageReasonFun = async () => {
  try {
    let res = await getDamageReason();
    if (res.code == 200) {
      damageReason.value = res.data.datas;
    } else {
      uni.showToast({
        title: res.msg,
        icon: "none",
      });
      // showToast(res.msg);
    }
  } catch (e) {
    uni.showToast({
      title: e.msg,
      icon: "none",
    });
    // showToast(e.msg);
  }
};

const damageReasonConfirm = (e) => {
  console.log("e", e);
  itemObj.value.damageReasonId = e.value[0].id;
  itemObj.value.damageReason = e.value[0].name;
  damageReasonShow.value = false;
};

//报损提交
const shoRow = ref(false);
const textValue = ref("");
const numValue = ref("");
const priceValueToa = ref("");
</script>

<template>
  <topNav
    title="商品搜索"
    @save="saveFun"
    rType="cancel"
    @search="searchFun"
    @scan="scanFun"
    :IsSearch="true"
    :code="code"
  ></topNav>

  <jia-PayKeyboard
    :confirmStyle="{ backgroundColor: '#1679FB' }"
    class="keyWord-index"
    :overlayClose="true"
    ref="keyWord"
    v-model="priceValue"
    :sclectItem="selectNumIndex"
    @del="del"
    @input="inp"
    @confirm="confirm"
    @hide="hide"
  >
    <view class="PayKeyboard-k" @click="showInputSelect = false">
      <view class="icon-top">
        <up-icon
          @click="closePay"
          name="close"
          color="#86909C"
          size="20"
        ></up-icon
      ></view>
      <view class="PayKeyboard-k-title">
        <view class="PayKeyboard-k-title-left">
          <image
            :src="
              itemObj.image
                ? itemObj.image
                : 'https://cloud-erp.yibaitao.cn/0d2f4178-7754-4686-9213-b174f745258b.png'
            "
            mode="scaleToFill"
          />
        </view>
        <view class="PayKeyboard-k-title-right">
          <view class="PayKeyboard-k-title-name"
            ><text>{{ itemObj.name }}</text>
          </view>
          <view class="PayKeyboard-k-title-des">
            <text v-if="itemObj.barCode">
              商品码:{{ itemObj.barCode ? itemObj.barCode : "" }}</text
            >
            <text v-if="itemObj.dhCode"> 称码:{{ itemObj.dhCode }}</text>
            <text>
              ¥{{ itemObj.taxPrice }}
              {{ itemObj.unit ? "/" + itemObj.unit : "" }}
            </text>
            <text>
              <text style="color: #86909c">库存:</text
              >{{ itemObj.stockNum }}</text
            >
          </view>
        </view>
      </view>
      <!-- <view class="PayKeyboard-k-des">{{ itemObj.barCode }}</view> -->
      <view class="link-to"></view>

      <view class="content-list">
        <view class="content-list-sel">
          <view class="content_info_index">
            <text class="content_info_index_text"
              >报损凭证<text style="color: #ff0000">*</text></text
            >
            <view class="bj">
              <up-upload
                :fileList="itemObj.damageCertificate"
                @afterRead="afterRead"
                @delete="deletePic"
                name="1"
                multiple
                ref="uUpload"
                accept="image"
                :previewFullImage="true"
                :maxCount="1"
              ></up-upload
            ></view>
          </view>
          <view class="content_info_index">
            <text class="content_info_index_text"
              >报损数量<text style="color: #ff0000">*</text></text
            >
            <view style="display: flex; align-items: center">
              <view
                class="bj bj2"
                @click.stop="
                  showInputSelect = true;
                  selectNumIndex = -1;
                "
              >
                <view class="PayKeyboard-k-num-input-text">
                  <view
                    class="num-view"
                    v-for="(item, index) in priceValue"
                    :key="index"
                    @click.stop="keyWordItem(index)"
                    ><view
                      class="input_lin"
                      v-if="selectNumIndex == index && showInputSelect"
                    ></view
                    >{{ item }}</view
                  >
                  <view
                    class="input_lin"
                    v-if="selectNumIndex == -1 && showInputSelect"
                  ></view> </view></view
              ><text>{{ itemObj.unit ? "/" + itemObj.unit : "" }}</text>
            </view>
          </view>

          <view class="content_info_index" @click="damageReasonShow = true">
            <text class="content_info_index_text"
              >报损理由<text style="color: #ff0000">*</text></text
            >
            <view class="bj"
              ><text :class="itemObj.damageReason ? 'color_in' : ''">{{
                itemObj.damageReason ? itemObj.damageReason : "选择报损理由"
              }}</text>
              <up-icon name="arrow-right" color="#C9CDD4" size="40rpx"></up-icon
            ></view>
          </view>
        </view>
      </view>
      <!-- <view class="PayKeyboard-k-num">
          <view class="PayKeyboard-k-num-title">新售价</view>
          <view class="PayKeyboard-k-num-input">
            <up-form labelPosition="left" ref="form1" labelWidth="0">
              <up-form-item
                label=" "
                borderBottom
                ref="item1"
                @click="keyWordItem(-1)"
              >
                <view class="PayKeyboard-k-num-input-text">
                  <view
                    class="num-view"
                    v-for="(item, index) in priceValue"
                    :key="index"
                    @click.stop="keyWordItem(index)"
                    ><view
                      class="input_lin"
                      v-if="selectNumIndex == index"
                    ></view
                    >{{ item }}</view
                  >
                  <view class="input_lin" v-if="selectNumIndex == -1"></view>
                </view>
                <template #right>
                  <text>元</text>
                </template>
              </up-form-item>
            </up-form>
          </view>
        </view> -->
    </view>
  </jia-PayKeyboard>
  <view class="goods_form">
    <view
      class="scroll-Y-item"
      v-for="(item, index) in productData"
      :key="index"
      @click="onClickItem(item, index)"
    >
      <view class="scroll-item-left">
        <image :src="item.image" mode="scaleToFill" />
      </view>
      <view class="scroll-item-right">
        <view class="goods-item-title"> {{ item.name }} </view>
        <view class="goods-item-spec" v-if="item.barCode">
          商品码:{{ item.barCode ? item.barCode : "" }}</view
        >
        <view class="goods-item-spec" v-if="item.dhCode">
          称码:{{ item.dhCode }}</view
        >
        <view class="goods-item-price">
          <text
            >¥{{ item.taxPrice ? item.taxPrice : 0.0 }}
            {{ item.unit ? "/" + item.unit : "" }}
            <text style="color: #86909c">库存:</text> {{ item.stockNum }}</text
          >
          <text v-if="item.bcStockNum" class="color-blue"
            >已选{{ item.bcStockNum }}</text
          >
        </view>
      </view>
    </view>
    <!-- <view
      class="scroll-Y-item"
      v-for="(item, index) in productData"
      :key="index"
      @click="onClickItem(item, index)"
    >
      
      <view class="scroll-item-right">
        <view class="goods-item-title"
          ><text>{{ item.name }}</text>
          <text v-if="item.newsalePrice">原价:{{ item.salePrice }}</text>
        </view>
        <view class="goods-item-price">
          <text> 条形码: {{ item.barCode ? item.barCode : "--" }}</text>
          <text class="color-blue"
            >¥{{
              item.newsalePrice
                ? item.newsalePrice
                : item.salePrice
                ? item.salePrice
                : "--"
            }}{{ item.unit ? "/" + item.unit : "" }}</text
          >
        </view>
      </view>
    </view> -->
  </view>
  <!-- v-if="productData.length <= 0 && !loading" -->
  <view class="noData" v-if="productData.length <= 0 && loading == 'noMore'">
    <view class="noData-img">
      <image src="@/static/nodate/datas.png" mode="scaleToFill" />
      <view>暂无商品 </view>
    </view>
  </view>

  <view class="loading-form" v-if="loading && productData.length > 0"
    ><van-loading size="24rpx" v-if="loading == 'Loading'"
      ><text class="loading-text">加载中...</text>
    </van-loading>
    <text class="loading-text" v-if="loading == 'More'">加载更多</text>
    <text class="loading-text" v-if="loading == 'noMore'">~没有数据了~</text>
  </view>
  <view style="width: 100%; height: 200rpx"></view>
  <view class="goods_bt">
    <view class="goods_bt_to">
      <text>共报损{{ products.length }}款商品,数量合计{{ numValue || 0 }}</text>
      <van-button class="val-button" type="primary" @click="goRecordone"
        >确认报损</van-button
      >
    </view>
  </view>

  <!-- <view class="mask-k" v-if="show" @click="show = false"></view> -->
  <!--  -->
  <!-- <view
    class="select_price"
    :style="'bottom:' + keyboardHeight + 'px;'"
    :class="!show ? 'select_price_noshow' : ''"
  >
    <view class="select_price_tag" @click="show = false">
      <van-icon name="cross" size="28rpx" color="#86909C" />
    </view>
    <view class="select_price_top">
      <view class="select_price_title">{{ itemObj.name }}</view>
      <view class="select_price_des">{{ itemObj.barCode }}</view>
    </view>
    <view class="select_price_in">
      <view class="select_price_title">新售价 </view>
      <view>
        <van-field
          v-model="priceValue"
          readonly
          clickable
          @touchstart.stop="show = true"
          class="select_price_input"
        >
          <template #button>
            <text>元</text>
          </template>
        </van-field>
      </view>
    </view>
  </view>
  <van-config-provider :theme-vars="themeVars">
    <van-number-keyboard
      :transition="true"
      :hide-on-click-outside="false"
      ref="keyboard"
      class="priceKey"
      v-model="priceValue"
      :show="show"
      theme="custom"
      extra-key="."
      close-button-text="完成"
      @blur="onBlue"
      @input="onInput"
      @delete="onDelete"
      z-index="50"
    />
  </van-config-provider> -->

  <up-popup
    :show="shoRow"
    mode="center"
    round="15"
    :closeOnClickOverlay="true"
    @close="shoRow = false"
  >
    <view class="popup_box">
      <view class="popup_title">
        <view>共报损{{ products.length }}款,数量{{ numValue }}</view>
        <view>合计进货价¥{{ priceValueToa }}</view>
        <view> 确认报损？</view>
      </view>
      <view class="popup_content">
        <up-textarea
          v-model="textValue"
          placeholder="请输入报损备注"
          maxlength="140"
        ></up-textarea>
      </view>
      <up-button class="popup_button" @click="goRecord()">提交报损</up-button>
    </view>
  </up-popup>

  <up-picker
    @cancel="damageReasonShow = false"
    @confirm="damageReasonConfirm"
    :show="damageReasonShow"
    :columns="[damageReason]"
    keyName="name"
  ></up-picker>
  <view class="show-camera" v-if="ishowcamera">
    <view class="show-camera-k">
      <view class="show-sm"> 设备权限使用说明 </view>
      <view class="show-des">
        为了给您带来更好的服务，需要获取您的相机权限与读取图片及文件权限，用于更换上传图片、扫一扫等功能，对于您授权的信息我们竭尽全力提供安全保护。
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
@import "./index.scss";
</style>
